package com.idp.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.idp.mapper.UsersMapper;
import com.idp.pojo.MyUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author JTR -H
 * @Address BS_221
 * @Created_Date 2021/7/27 - 16:38
 */
@Service // 无值则默认 ("myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(MyUserDetailsService.class);

    @Autowired
    @Qualifier("getEncoder")
    BCryptPasswordEncoder encoder;

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 构建查询器
        QueryWrapper<MyUser> wrapper = new QueryWrapper<>();
        // where username = ?
        wrapper.eq("username", username);
        // select username ... limit 1
        MyUser myUser = usersMapper.selectOne(wrapper);

        if (myUser == null) {
            UsernameNotFoundException e = new UsernameNotFoundException("用户名不存在!!!");
            logger.error("用户名不存在!!!", e);
            throw e;
        }

        List<GrantedAuthority> roleList = AuthorityUtils
                .commaSeparatedStringToAuthorityList(myUser.getAuthority());

        // User类的密码是加密后的.
        // 在这个类中实现了密码校验. 传入的是正确密码
        return new User(myUser.getUsername(), encoder.encode(myUser.getPassword()), roleList);
    }
}


/*
 ******************************************************
 *    Eliminate all impossible,                       *
 *    remain that although or else can be thought of, *
 *    discuss,                                        *
 *    that also is a fact.                            *
 ******************************************************
 */
